// Copyright 2007 Google, Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.io;

import com.google.jessewilson.codesearch.api.CodeFile;
import com.google.jessewilson.codesearch.api.SearchProviderException;
import com.google.jessewilson.codesearch.api.spi.SearchProviderBackend;

import java.io.File;
import java.io.IOException;

/**
 * Manage the download of a file. 
 *
 * @author jessewilson
 */
public class FileDownloader {

  private final SearchProviderBackend searchProviderBackend;

  public FileDownloader(SearchProviderBackend searchProviderBackend) {
    this.searchProviderBackend = searchProviderBackend;
  }

  public Result download(CodeFile codeFile) {
    try {
      String shortName = codeFile.getPath().getFileName();
      File localFile = File.createTempFile(shortName, "codesearch");
      localFile.deleteOnExit();
      searchProviderBackend.downloadFile(codeFile, localFile);
      return new Result(codeFile, localFile);
    } catch (IOException e) {
      return new Result(codeFile, e);
    } catch (SearchProviderException e) {
      return new Result(codeFile, e);
    }
  }

  public class Result {
    private final CodeFile codeFile;
    private final File localFile;
    private final Exception exception;

    public Result(CodeFile codeFile, File localFile) {
      this.codeFile = codeFile;
      this.localFile = localFile;
      this.exception = null;
    }

    public Result(CodeFile codeFile, Exception exception) {
      this.codeFile = codeFile;
      this.localFile = null;
      this.exception = exception;
    }

    public boolean isSuccess() {
      return localFile != null;
    }

    public File getLocalFile() {
      return localFile;
    }

    public CodeFile getCodeFile() {
      return codeFile;
    }

    public Exception getException() {
      return exception;
    }
  }
}
